﻿@{
    ViewData["Title"] = "发票管理系统";
}

<div class="text-center">
    <h1 class="display-4">欢迎来到发票管理系统</h1>
</div>

<!-- 发票表单 -->
<form id="invoiceForm" onsubmit="submitInvoice(event)">
    <div>
        <label for="amount">金额:</label>
        <input type="number" id="amount" name="amount" required />
    </div>
    <div>
        <label for="category">类别:</label>
        <select id="category" name="category">
            <option value="餐饮">餐饮</option>
            <option value="交通">交通</option>
            <!-- 其他类别选项 -->
        </select>
    </div>
    <div>
        <label for="invoiceFile">上传发票:</label>
        <input type="file" id="invoiceFile" name="invoiceFile" required />
    </div>
    <button type="submit">提交</button>
</form>

<!-- 总金额显示 -->
<h2 id="totalAmount">总金额: 0</h2>

<!-- 新增：计算后的总金额显示 -->
<span id="calculatedTotalAmount">总金额: 未知</span>

<!-- 下载链接列表 -->
<div id="invoiceList"></div>

@section Scripts {
    <script>
        async function submitInvoice(event) {
            event.preventDefault(); // 阻止表单默认提交行为
            
            var amount = document.getElementById('amount').value;
            var category = document.getElementById('category').value;
            var invoiceFile = document.getElementById('invoiceFile').files[0];

            if (invoiceFile) {
                var formData = new FormData();
              
                formData.append('file', invoiceFile);
                formData.append('category', category);
                formData.append('amount', amount);

                try {
                    var response = await fetch('/api/invoices/upload', {
                        method: 'POST',
                        body: formData
                    });
                    var result = await response.json();
                    if (response.ok) {
                        alert(result.Message);
                        await updateTotalAmount();
                        addDownloadLink(result.InvoiceId);
                    } else {
                        alert(result.Message);
                    }
                } catch (error) {
                    console.error('Error:', error);
                }
            }
        }

      
        function addDownloadLink(invoiceId) {
            var link = document.createElement('a');
            link.href = `/api/invoices/download/${invoiceId}`;
            link.textContent = `下载发票 #${invoiceId}`;
            link.target = '_blank';
            document.getElementById('invoiceList').appendChild(link);
            document.getElementById('invoiceList').appendChild(document.createElement('br'));
        }

        页面加载时获取总金额
       document.addEventListener('DOMContentLoaded', updateTotalAmount);
    </script>
}
